
export default {
  data() {
    return {
      rawData: [/* 原始数据 */],
      reversedTree: []
    }
  },
  created() {
    this.buildReversedTree();
  },
  methods: {
    buildReversedTree() {
      const nodeMap = new Map();
      const reverseMap = new Map();
      const visited = new Set();

      // 构建双向映射关系
      this.rawData.forEach(item => {
        // 正向映射：daogongxuid -> node
        if (!nodeMap.has(item.daogongxuid)) {
          nodeMap.set(item.daogongxuid, {
            ...item,
            originalChildren: new Set(),
            mergedChildren: []
          });
        }

        // 反向映射：bengongxuid -> parents
        if (!reverseMap.has(item.bengongxuid)) {
          reverseMap.set(item.bengongxuid, new Set());
        }
        reverseMap.get(item.bengongxuid).add(item.daogongxuid);
      });

      // 找出所有叶子节点（没有子节点的节点）
      const roots = Array.from(nodeMap.keys()).filter(daogongxuid => {
        return !reverseMap.has(daogongxuid) || 
               reverseMap.get(daogongxuid).size === 0;
      });

      // 递归构建树
      const buildTree = (currentId) => {
        if (visited.has(currentId)) return null;
        visited.add(currentId);

        const currentNode = nodeMap.get(currentId);
        if (!currentNode) return null;

        const treeNode = {
          ...currentNode,
          children: []
        };

        // 获取所有父节点（原bengongxuid对应的所有daogongxuid）
        const parents = reverseMap.get(currentNode.bengongxuid) || new Set();
        
        parents.forEach(parentId => {
          const childTree = buildTree(parentId);
          if (childTree) {
            // 合并相同daogongxuid的子节点
            const existing = treeNode.children.find(
              c => c.daogongxuid === childTree.daogongxuid
            );
            
            if (!existing) {
              treeNode.children.push(childTree);
            } else {
              // 合并子节点的children
              existing.children = [
                ...existing.children,
                ...childTree.children
              ].filter((v, i, a) => 
                a.findIndex(t => t.daogongxuid === v.daogongxuid) === i
              );
            }
          }
        });

        return treeNode;
      };

      // 构建完整树结构
      let reversedTree = roots.map(root => buildTree(root)).filter(Boolean);
      console.log("reversedTree:", reversedTree)
    }
  }
}
